// ====== 工具：localStorage 存取 ======
const load = (k, def) => {
  try { return JSON.parse(localStorage.getItem(k)) ?? def; }
  catch { return def; }
};
const save = (k, v) => localStorage.setItem(k, JSON.stringify(v));

// ====== 初始数据 ======
if (!localStorage.getItem("products")) save("products", [
  { id: 1, title: "二手教材《计算机基础》", price: 35, seller: "alice" },
  { id: 2, title: "二手鼠标", price: 50, seller: "bob" },
  { id: 3, title: "台灯", price: 25, seller: "carol" },
  { id: 4, title: "书包", price: 80, seller: "dave" }
]);

const store = {
  products: load("products", []),
  cart: load("cart", []),
  currentUser: load("currentUser", null)
};

// ====== 通用函数 ======
const findProduct = id => store.products.find(p => p.id === id);

// ====== 首页：渲染商品 ======
function renderProducts(list = store.products) {
  const box = document.getElementById("product-list");
  if (!box) return;
  box.innerHTML = "";
  list.forEach(p => {
    const card = document.createElement("div");
    card.className = "product-card";
    card.innerHTML = `
      <h3>${p.title}</h3>
      <p class="price">￥${p.price}</p>
      <p>卖家：${p.seller}</p>
      <button onclick="addToCart(${p.id})">加入购物车</button>
    `;
    box.appendChild(card);
  });
}

// ====== 搜索 ======
function searchProducts() {
  const kw = document.getElementById("search-input").value.trim().toLowerCase();
  const filtered = store.products.filter(p =>
    p.title.toLowerCase().includes(kw) || p.seller.toLowerCase().includes(kw)
  );
  renderProducts(filtered);
}

// ====== 购物车：加入 ======
function addToCart(id) {
  const p = findProduct(id);
  if (!p) return;
  const exist = store.cart.find(i => i.id === id);
  if (exist) exist.quantity++;
  else store.cart.push({ ...p, quantity: 1 });
  save("cart", store.cart);
  alert("已加入购物车");
}

// ====== 购物车：渲染 ======
function renderCart() {
  const tbody = document.querySelector("#cart-table tbody");
  const totalEl = document.getElementById("total-price");
  if (!tbody || !totalEl) return;
  tbody.innerHTML = "";
  let total = 0;
  store.cart.forEach((item, idx) => {
    const sub = item.price * item.quantity;
    total += sub;
    const tr = document.createElement("tr");
    tr.innerHTML = `
      <td>${item.title}</td>
      <td>￥${item.price}</td>
      <td>
        <button onclick="changeQty(${idx},-1)">-</button>
        ${item.quantity}
        <button onclick="changeQty(${idx},1)">+</button>
      </td>
      <td>￥${sub}</td>
      <td><button onclick="removeFromCart(${idx})">删除</button></td>
    `;
    tbody.appendChild(tr);
  });
  totalEl.textContent = `总价：${total} 元`;
}

// ====== 数量变化 & 删除 ======
function changeQty(index, delta) {
  const item = store.cart[index];
  item.quantity += delta;
  if (item.quantity <= 0) store.cart.splice(index, 1);
  save("cart", store.cart);
  renderCart();
}
function removeFromCart(index) {
  store.cart.splice(index, 1);
  save("cart", store.cart);
  renderCart();
}

// ====== 页面加载时初始化 ======
document.addEventListener("DOMContentLoaded", () => {
  if (location.pathname.endsWith("index.html")) renderProducts();
  if (location.pathname.endsWith("cart.html")) renderCart();
});